package Sort.sort2020_2;

import util.SwapUtil;

/**
 * 堆排序
 * 从小到大
 * @author: leiwenkang
 * @date: 2020/5/23
 * @time: 18:17
 */
public class HeapSort {

    public static void main(String[] args) {
        int[] array = {3,8,4,6,7,2,5,9,1};
        sort(array);
        for (int i = 0; i < array.length; i++){
            System.out.print(array[i]);
            System.out.print(" ");
        }
    }

    public static void sort(int[] array) {
        if (array == null || array.length == 0) {
            return;
        }

        //建最大堆
        for (int i = array.length / 2 - 1; i >= 0; i--) {
            adjustHeap(array, i, array.length - 1);
        }

//        for (int i = array.length - 1; i >= 0; i--) {
//            SwapUtil.swap(array, 0, i);
//            adjustHeap(array, 0, i - 1);
//        }                                                                                                                                     .…''
    }

    private static void adjustHeap(int[] array, int index, int end) {
        for (int i = 2 * index + 1; i <= end; i = 2 * i + 1) {
            if (i < end && array[i] < array[i + 1]) {
                //与根结点交换
                i++;
            }

            if (array[i] < array[index]) {
                break;
            }
            SwapUtil.swap(array, i, index);
            index = i;
        }
    }
}
